package com.lipaluma.field.validator.impl.Enum;

import java.lang.reflect.Field;

import com.lipaluma.annotations.validations.Validate;
import com.lipaluma.context.Context;
import com.lipaluma.field.validator.impl.generic.AbstractConstantValidator;
import com.lipaluma.util.ParserUtils;
import com.lipaluma.util.ReflectionUtils;
import com.lipaluma.xml.validator.XmlConstantValidator;
import com.lipaluma.xml.validator.XmlValidator;

/**
 * Validate an enum type field to check if all value for the field is constant.<br/>
 * A value can be supplied or not. 
 * <ul>
 * <li>If the value is supplied, all values of the source must be equal to that value</li>
 * <li>If not, the first value encountered will be the constant to respect for all others.</li>
 * </ul>
 * 
 * <p>
 * For Initialisation :
 * <ul>
 * 	<li>
 * 	<u><b>By annotations :</b></u> Use {@link Validate}, with the attribute <code>constant = true</code>. <br/>
 * To supply a value, put <code>constantSupplied = true</code> and the value supplied in <code>constantValue</code> attribute.<br/>
 * The supplied value must match the name of the enum.<br/>
 * </li>
 * 	<li>
 * 	<u><b>By Xml :</b></u>
 * <ul>
 * <li>
 * See the example below to add a constant validator without supplied value : <br/>
 * <code>
 * &lt;ToMap field="..."   ...><br/>
 * &nbsp;&nbsp;&nbsp;<b>&lt;constant/></b><br/>
 * &lt;/ToMap>
 * </code>
 * <br/>
 * </li>
 * <li>
 * See this other example to add a constant validator with a supplied value : <br/>
 * <code>
 * &lt;ToMap field="..."   ...><br/>
 * &nbsp;&nbsp;&nbsp;<b>&lt;constant>VALUE_OF_ENUM&lt;/constant></b><br/>
 * &lt;/ToMap>
 * </code>
 * <br/>
 * </li>
 * </li>
 * </ul>
 * @author Mario
 *
 */
public class EnumConstantValidator extends AbstractConstantValidator<Object> {

	public EnumConstantValidator() {}
	public EnumConstantValidator(Enum<?> value) {
		init(value);
	}

	@Override
	public boolean init(Context context, Field field) {
		Validate annotation = field.getAnnotation(Validate.class);
		if(annotation == null || !annotation.constant())
			return false;
		
		if(annotation.constantSupplied()) {
			init(ParserUtils.parseToEnum(ReflectionUtils.getParameterizedClass(field), annotation.constantValue()));
		}
		return true;
	}

	@Override
	public boolean init(Context context, Field field, XmlValidator xmlValidator) {
		XmlConstantValidator validator = (XmlConstantValidator) xmlValidator;
		if(validator.getConstantValue() != null)
			init(ParserUtils.parseToEnum(field.getType(), validator.getConstantValue()));
		return true;
	}	

}
